<script setup>
import {onMounted, ref} from 'vue'
import {QueryArea,DeleteareApi,AddareAPi,UpdateApi} from '@/api/warehouse_area'
import{QueryPageApi}from '@/api/warehouse'
import{ElMessage} from 'element-plus'

const dialogVisible=ref(false)
const disForm=ref({
  warehousename:'',
  name:'',
  category:''
})

// 新增：仓库列表数据
const warehouseList = ref([])

// 新增：编辑状态相关变量
const currentEditId = ref(null)
const isEdit = ref(false)

//给搜索框赋值
const areaform=ref({
  name:'',
  warehousename:''
})
const total=ref(0)
const currentPage=ref(1)
const pageSize=ref(10)
const areaDate=ref([])

// 新增获取仓库列表
const fetchWarehouseList = async () => {
  try {
    const res = await QueryPageApi(1, 1000, '', '')
    if (res.code) {
      warehouseList.value = res.data.list
    }
  } catch (error) {
    ElMessage.error('获取仓库列表失败')
  }
}

const search=async()=>{ 
  const result=await QueryArea(currentPage.value,
    pageSize.value,
    areaform.value.warehousename,
    areaform.value.name)
  if(result.code){
    areaDate.value=result.data.list
    total.value=result.data.total
  }else{
    ElMessage.error("失败")
  }
}

const add=async()=>{ 
  // 清空表单，设置为新增状态
  disForm.value = {
    warehousename: '',
    name: '',
    category: ''
  }
  isEdit.value = false
  currentEditId.value = null
  dialogVisible.value = true
}

const handleEdit=async(index,row)=>{ 
  // 填充表单数据，设置为编辑状态
  disForm.value = {
    ...row
  }
  currentEditId.value = row.id
  isEdit.value = true
  dialogVisible.value = true
}

const handleDelete=async(index,row)=>{ 
  let res=await DeleteareApi(row.id)
  if(res){
    ElMessage.success("删除成功")
    search()
  }else{
    ElMessage.error("删除失败")
  }
}

// 页码大小改变时的回调
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  search()
}

// 当前页改变时的回调
const handleCurrentChange = (val) => {
  currentPage.value = val
  search()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 保存数据函数
const save = async () => {
  try {
    // 从仓库列表中查找选中的仓库
    const selectedWarehouse = warehouseList.value.find(
      warehouse => warehouse.name === disForm.value.warehousename
    )
    
    if (!selectedWarehouse) {
      ElMessage.error('请选择有效的仓库')
      return
    }

    // 准备请求参数
    const params = {
      warehouseId: selectedWarehouse.id,
      name: disForm.value.name,
      category: disForm.value.category
    }
    
    let res
    // 判断是新增还是更新
    if (isEdit.value && currentEditId.value) {
      // 更新操作需要传入ID
      params.id = currentEditId.value
      res = await UpdateApi(params)
    } else {
      // 新增操作
      res = await AddareAPi(params)
    }
    
    if (res.code == 1 || res.code == 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
      search()
    } else {
      ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

onMounted(()=>{
  search()
  fetchWarehouseList() // 获取仓库列表
})
</script>

<template>
  <!--搜索栏-->
  <el-form :model="areaform" :inline="true" label-width="auto" style="max-width: 600px">
    <el-form-item>
      <el-input v-model="areaform.name" placeholder="库区名称"/>
    </el-form-item>
    <el-form-item>
      <el-input v-model="areaform.warehousename" placeholder="仓库名称" clearable/>
    </el-form-item>
    <el-button type="success" @click="search">查询</el-button>
    <el-button type="success" @click="add">+</el-button>
  </el-form>

  <!--表格数据-->
  <el-table :data="areaDate" style="width: 100%">
    <el-table-column prop="id" type="index" label="#" width="55px" />
    <el-table-column type="selection" width="55px" />
    <el-table-column prop="warehousename" label="仓库名称" width="180" />
    <el-table-column prop="name" label="库区名称" width="180" />
    <el-table-column prop="category" label="库区类型" />
    <el-table-column prop="isDel" label="是否有效" />
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          修改
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  
  <!--分页-->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!--对话框-->
  <el-dialog
    v-model="dialogVisible"
    title="库区信息"
    width="500"
    :before-close="handleClose"
  >
    <template #footer>
      <el-row :gutter="20">
        <el-form :model="disForm" style="max-width: 800px">
          <el-col :span="24">
            <el-form-item>
              <!-- 修改：仓库名称输入框改为下拉选择 -->
              <el-select v-model="disForm.warehousename" placeholder="仓库名称">
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-select v-model="disForm.category" placeholder="库区类型">
                <el-option label="收获区" value="RECEIVING" />
                <el-option label="存储区" value="STORAGE" />
                <el-option label="发货区" value="SHIPPING" />
                <el-option label="退货区" value="RETURN" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-input v-model="disForm.name" placeholder="库区名称">
            </el-input>
          </el-col>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </el-row>
    </template>
  </el-dialog>
</template>

<style>
/* 可以在这里添加样式 */
</style>